﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Abp.AutoMapper;
using Abp.Domain.Repositories;
using Xugege.AbpExtension.Application.Extension.DataDictionary.Dto;
using Xugege.AbpExtension.Core.Extension.DataManager;
using Abp.UI;
using System.Data.Entity;
using Abp.Extensions;

namespace Xugege.AbpExtension.Application.Extension.DataDictionary
{
    public class DictionaryCategoryService : AbpZeroTemplateAppServiceBase, IDictionaryCategoryService
    {

        private readonly IRepository<DataDictionaryCategory, int> _dictionaryCategory;
        private readonly IRepository<Xugege.AbpExtension.Core.Extension.DataManager.DataDictionary, long> _dictionaryService;

        public DictionaryCategoryService(IRepository<DataDictionaryCategory, int> dictionaryCategory,
            IRepository<Xugege.AbpExtension.Core.Extension.DataManager.DataDictionary, long> dictionaryService
            )
        {
            _dictionaryCategory = dictionaryCategory;
            _dictionaryService = dictionaryService;
        }

        /// <summary>
        /// 检查类别代码的唯一性
        /// </summary>
        /// <param name="input"></param>
        /// <returns>
        /// true 表示唯一
        /// </returns>
        public async Task<bool> CheckCategoryCode(DictionaryCategoryCodeInputDto input)
        {
            if (input.CategoryCode.IsNullOrEmpty())
            {
                throw new UserFriendlyException(L("ParamError"));
            }
            var sameCodeList = await _dictionaryCategory.GetAll().Where(m => m.CategoryCode == input.CategoryCode).ToListAsync();
            if (sameCodeList.Any())
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<int> Delete(DictionaryCategoryInputDto input)
        {
            if (input == null || !input.Id.HasValue)
            {
                throw new UserFriendlyException(L("ParamError"));
            }
            //判断类别下是否有数据 如果有不能删除
            DataDictionaryCategory category = await _dictionaryCategory.GetAsync(input.Id.Value);
            if (category == null)
            {
                throw new UserFriendlyException("对象不存在");
            }
            var dictionaries = _dictionaryService.GetAll().Where(m => m.CategoryCode == category.CategoryCode);
            if (dictionaries == null || !dictionaries.Any())
            {
                await _dictionaryCategory.DeleteAsync(input.Id.Value);
            }
            else
            {
                throw new UserFriendlyException("类别已经绑定数据，删除前请先确保清空数据！");
            }

            return input.Id.Value;
        }

        /// <summary>
        /// 获取所有的数据字典分类列表
        /// </summary>
        /// <returns></returns>
        public async Task<IList<DictionaryCategoryOutputDto>> GetDictionaryCategories()
        {
            return (await _dictionaryCategory.GetAllListAsync())
                .MapTo<IList<DictionaryCategoryOutputDto>>();
        }
        /// <summary>
        /// 解/锁
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task UnOrLock(DictionaryCategoryInputDto input)
        {
            if (input == null || !input.Id.HasValue)
            {
                throw new UserFriendlyException(L("ParamError"));
            }
            DataDictionaryCategory category = await _dictionaryCategory.GetAsync(input.Id.Value);
            if (category.TenantId == 0)
            {
                throw new UserFriendlyException(L("系统预设数据,不允许修改"));
            }
            category.Enabled = !category.Enabled;
            await _dictionaryCategory.UpdateAsync(category);
        }

        public async Task<DictionaryCategoryOutputDto> Update(DictionaryCategoryInputDto input)
        {
            input.TenantId = GetCurrentTenant().Id;
            if (input.Id.HasValue)
            {
                //编辑
                DataDictionaryCategory dbData = await _dictionaryCategory.GetAsync(input.Id.Value);
                if (dbData == null)
                {
                    throw new UserFriendlyException("实体不存在");
                }
                if (dbData.TenantId == 0)
                {
                    throw new UserFriendlyException(L("系统预设数据,不允许修改"));
                }
                dbData.Enabled = input.Enabled;
                dbData.Name = input.Name;
                dbData.Remark = input.Remark;
                dbData.LevelRule = input.LevelRule;
                return (await _dictionaryCategory.UpdateAsync(dbData)).MapTo<DictionaryCategoryOutputDto>();
            }
            else
            {
                // var sameCodeList = await _dictionaryCategory.GetAll().Where(m => m.CategoryCode == input.CategoryCode).ToListAsync();
                if (!(await CheckCategoryCode(new DictionaryCategoryCodeInputDto() { CategoryCode = input.CategoryCode })))
                {
                    throw new UserFriendlyException(L("类别代码必须唯一"));
                }
                //新增
                return (await _dictionaryCategory.InsertAsync(input.MapTo<DataDictionaryCategory>()))
                    .MapTo<DictionaryCategoryOutputDto>();
            }

        }


    }
}
